package com.wosiliujing.learning.service.impl;

import cn.hutool.core.collection.IterUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sun.org.apache.xpath.internal.operations.Bool;
import com.wosiliujing.learning.admin.dto.DeptTree;
import com.wosiliujing.learning.admin.po.SysUser;
import com.wosiliujing.learning.constant.CommonConstants;
import com.wosiliujing.learning.mapper.SysDeptMapper;
import com.wosiliujing.learning.admin.po.SysDept;
import com.wosiliujing.learning.service.SysDeptService;
import com.wosiliujing.learning.service.SysUserService;
import com.wosiliujing.learning.util.SecurityUtil;
import com.wosiliujing.learning.util.TreeUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.beans.Beans;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: liujing
 * @date: 2019/5/6 21:49
 * @description:
 */
@Slf4j
@AllArgsConstructor
@Service
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements SysDeptService {

    private final SysUserService sysUserService;


    /**
     * 构建相应部门的部门树
     * @param deptList 部门列表
     * @param deptId 父部门
     * @return 部门树
     */
    private List<DeptTree> buildDeptTree(List<SysDept> deptList,String deptId){
        List<DeptTree> treeList = deptList.stream()
                .filter(dept -> !StrUtil.equals(dept.getId(),dept.getParentId()))
                .map(dept -> {
                    DeptTree deptTree = new DeptTree();
                    BeanUtils.copyProperties(dept,deptTree);
                    return  deptTree;
                }).collect(Collectors.toList());
        return TreeUtil.buildTree(treeList, deptId);
    }

    @Override
    public List<DeptTree> listDeptTree() {
       return buildDeptTree(this.list(Wrappers.<SysDept>lambdaQuery().orderByDesc(SysDept::getSort)),CommonConstants.TREE_ROOT);
    }

    @Override
    public List<DeptTree> listCurrentUserDeptTree() {
        SysUser sysUser = sysUserService.getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUserId,SecurityUtil.getUser()));
        return buildDeptTree(this.list(Wrappers.<SysDept>lambdaQuery().orderByDesc(SysDept::getSort)),sysUser.getDeptId());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean saveSysDept(SysDept sysDept) {
        sysDept.setCreateTime(LocalDateTime.now());
        sysDept.setDelFlag(CommonConstants.NORMAL_STATUS);
        if(StrUtil.isBlank(sysDept.getParentId())){
            sysDept.setParentId(CommonConstants.TREE_ROOT);
        }
        return this.save(sysDept);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean deleteSysDept(String deptId) {
        List<String> childIds = this.list(Wrappers.<SysDept>lambdaQuery().eq(SysDept::getParentId,deptId))
                .stream().map(dept -> dept.getId()).collect(Collectors.toList());
        if(IterUtil.isNotEmpty(childIds)){
            childIds = getChildSysDeptIds(childIds);
        }else{
            childIds = new ArrayList<>();
            childIds.add(deptId);
        }
        return  this.removeByIds(childIds);
    }

    private List<String> getChildSysDeptIds(List<String> ids){
        List<String> deptIds = new ArrayList<>();
        deptIds.addAll(ids);
        ids.forEach(deptId -> {
            List<String> childIds = this.list(Wrappers.<SysDept>lambdaQuery().eq(SysDept::getParentId,deptId))
                    .stream().map(dept -> dept.getId()).collect(Collectors.toList());
            if(IterUtil.isNotEmpty(childIds)){
                deptIds.addAll(getChildSysDeptIds(childIds));
            }
        });
        return deptIds;
    }

}
